/*
 * automat.cpp
 *
 *  Created on: 2011-3-6
 *      Author: hao
 */

#include "automat.h"


Automat::Automat( int nState ){

	for( int i = 0; i < nState; i++ ){

		TransTable.push_back( HashTable<int>() );

	}

}

Automat::~Automat(){
}

int Automat::Run( char * pData, int len, int & start_pos ){

	int old_pos = start_pos;

	int state = 0;

	char c = pData[ start_pos++ ];

	while( TransTable[state][c] && start_pos < len ){

		if( ActionTable[ state ] )
			ActionTable[ state ]( pData, len, start_pos );

		state = TransTable[ state ][ c ];

		c = pData[ start_pos++ ];

	}

	unsigned index = 0;

	for( ; index < accState.size(); index++ ){

		if( accState[ index ] == state ) break;

	}

	if( index == accState.size() ){

		start_pos = old_pos;

		return -1;

	}

	return state;

}

void Automat::InsertState( int state, char cLookahead, int target_state, int ReturnValue ){

	TransTable[ state ].Insert( cLookahead, target_state );

	if( ReturnValue != 0 )
		TransTable[ state ].setNoThingReturn( ReturnValue );

}

void Automat::InsertAccState( int state ){

	accState.push_back( state );

}

void Automat::InsertAction( int state, function< void( char * data, int length, int pos ) > fun ){
	ActionTable.Insert( state, fun );
}


